unit testsave;

{$mode objfpc}{$H+}

interface

uses
  Classes,
  SysUtils,
  fpcunit,
  //testutils,
  testregistry,
  common;

type

  { TTestSave }

  TTestSave = class(TTestCase)
  private
    obj: TPerson;
    objlist: TPersonList;
  protected
    procedure SetUp; override;
    procedure TearDown; override;
  published
    procedure TestSaveObject;
    procedure TestSaveObjectListWithTransaction;
    procedure TestSaveWithRelation;
  end;

implementation

uses
  hadeexception;

procedure TTestSave.SetUp;
begin
  obj := TPerson.Create();
  objlist := TPersonList.Create();
end;

procedure TTestSave.TearDown;
begin
  FreeAndNil(obj);
  FreeAndNil(objlist);
end;

procedure TTestSave.TestSaveObject;
begin
  obj.First_Name := 'Standart';
  obj.Last_Name := 'Pen';
  obj.Age := 15;
  try
    session.save(obj);
  finally
    obj.MarkDelete();
    session.save(obj);
  end;
end;

procedure TTestSave.TestSaveObjectListWithTransaction;
var
  obj1: TPerson;
  obj2: TPerson;
begin
  obj1 := TPerson.Create(objlist);
  obj1.First_Name := 'Test';
  obj1.Last_Name := 'doank';
  obj1.Age := 463;

  obj2 := TPerson.Create(156, objlist);
  session.Read(obj2);
  obj2.First_Name := 'Test';
  obj2.Last_Name := 'lagi';
  obj2.Age := 54;
  obj2.MarkDirty();

  objlist.add(obj1);
  objlist.add(obj2);
  //session.StartTransaction;
  try
    session.save(objlist);
  except
    on E: EHadeDatabase do
    begin
      session.Rollback;
      fail('it should success!' + E.Message);
    end;
  end;
  session.commit;
  obj1.MarkDelete();
  session.save(obj1);//we delete again obj1
end;

procedure TTestSave.TestSaveWithRelation;
var
  objAddress: TAddress;
begin
  obj.First_Name := 'Test1';
  obj.Last_Name := 'doank';
  obj.age := 45;
  objAddress := TAddress.Create(obj);
  objaddress.Email := 'asdasd@cendol.com';
  objaddress.Phone := 54354;

  obj.Address := objaddress;//put objaddress on obj
  //session.StartTransaction;
  try
    session.save(objaddress);//save objaddress first
    session.save(obj);//save obj
  except
    on E: EHadeDatabase do
    begin
      session.Rollback;
      fail('it should success!' + E.Message);
    end;
  end;
  session.Commit;
end;

initialization
  RegisterTest(TTestSave);
end.

